package com.white.commonlib.manager;

import android.app.Activity;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by ytf on 2016/12/8.
 * descption: activity管理类
 */

public class AppManager
{
    private AppManager()
    {
        listActivities = new ArrayList<>();
    }

    private static AppManager instance;
    private List<Activity> listActivities;

    public static AppManager getInstance()
    {
        if(instance == null)
        {
            synchronized (AppManager.class)
            {
                if(instance == null)
                {
                    instance = new AppManager();
                }
            }
        }
        return instance;
    }

    public int size()
    {
        return listActivities.size();
    }

    public void put(Activity activity)
    {
        listActivities.add(activity);
    }

    /***
     * 弹出顶层activity，同时会从栈中移除，一般用于activity销毁时调用
     * @return
     */
    public void pop()
    {
        if(listActivities.size() > 0)
        {
            int size = listActivities.size();
            if(size > 1)
            {
                listActivities.remove(size - 1);
            }else
            {
                listActivities.remove(0);
            }
        }
    }

    /***
     * 弹出顶层activity，不会从栈中移除
     * @return
     */
    public Activity getTop()
    {
        if(listActivities.size() > 0)
        {
            int size = listActivities.size();
            Activity a = null;
            if(size > 1)
            {
                a = listActivities.get(size - 1);
                if(isAlive(a))
                    return a;
            }else
            {
                a = listActivities.get(0);
                if(isAlive(a))
                    return a;
            }
        }
        return null;
    }

    private boolean isAlive(Activity a)
    {
        return a != null && !a.isDestroyed() && !a.isFinishing();
    }

    /***
     * 清空activity栈
     */
    public void termilate()
    {
        if(listActivities.size() > 0)
        {
            int size = listActivities.size();
            for(int i = size-1; i >= 0 ;i--)
            {
                Activity a = listActivities.get(i);
                if(isAlive(a))
                {
                    a.finish();
                    LogManager.e(a.getLocalClassName() + "调用finish-----");
                }
            }
        }
    }
}
